<template>
	<view class="u-page">
		<!-- 顶部状态栏占位 -->
		<view class="status-bar-placeholder"></view>
		<!-- 顶部标题栏 -->
		<view class="header" style="height:auto; padding-top: 10px;">
			<view class="custom-icon-badge" @click="handleIconClick">
				<up-icon name="bell-fill" size="25" color="#fff" />
				<view class="custom-badge" v-if="userInfo.tipCount > 0">{{ userInfo.tipCount }}</view>
			</view>
		</view>
		<!-- 顶部标题栏 -->
		<view class="header">
			<text class="header-title">薪管家，您的薪资发放管家！</text>
		</view>
		<!-- 资产信息卡片 -->
		<view class="asset-card">
			<view class="asset-header">
				<view class="asset-title-container">
					<text class="asset-title">我的资产(元)</text>
					<up-icon :name="showAsset ? 'eye-fill' : 'eye-off'" size="18" color="#333" @click="toggleAssetVisibility"/>
					<view class="asset-tag">最高年化收益率{{assetData.rate }}%</view>
				</view>
			</view>
			
			<view class="asset-amount" @click="publicNavigate('/pages/my/asset')">
				<text>{{ showAsset ? userInfo.amount : '****' }}</text>
				<up-icon name="arrow-right" size="18" color="#333" class="amount-arrow"/>
			</view>
			
			<view class="asset-details">
				<view class="asset-detail-item">
					<text class="detail-label">昨日收益(元)</text>
					<text class="detail-value">{{ showAsset ? userInfo.lastAmountAdd??0 : '**' }}</text>
				</view>
				<view class="asset-detail-divider"></view>
				<view class="asset-detail-item">
					<text class="detail-label">累计收益(元)</text>
					<text class="detail-value">{{ showAsset ? userInfo.amountAddSum??0 : '**' }}</text>
				</view>
			</view>
		</view>
		<!-- 顶部提示信息 -->
		<!-- <up-notice-bar text="新管家，您的薪资发放管家！" bgColor="#1989fa" color="#fff" speed="100"/> -->
		
		<!-- 工资列表容器 -->
		<up-pull-refresh :refreshing="refreshing" @refresh="onRefresh" :head-height="30">
			<up-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
				<up-list-item v-for="(item, index) in salaryList" :key="index" class="salary-item">
					<!-- 员工信息 -->
					<view class="employee-info">
						<text class="employee-name">{{ item.name }}</text>
						<view class="position-tag">{{ item.jobname }}</view>
						<text class="month">{{ monthFormat(item.month) }}</text>
					</view>
					
					<!-- 底部信息容器 -->
				<view class="bottom-container">
					<!-- 薪资信息 -->
					<view class="salary-amount">
						<text class="amount-label">本月应发工资：</text>
						<text class="amount-value">{{ item.realSalary }}元</text>
					</view>
					
					<!-- 状态显示 -->
					<view class="status-display" @click="goToDetail(item.id)">
						<text class="status-text" :class="getStatusClass(item.state)">{{ getStatusText(item.state) }}</text>
						<up-icon name="arrow-right" size="14" color="#666"/>
					</view>
				</view>
				</up-list-item>
			</up-list>
		</up-pull-refresh>
	</view>
</template>

<script setup>
	import { onShow } from "@dcloudio/uni-app"
	import { ref, onMounted, reactive } from 'vue';
	import { getListByVo } from '../../api/salary';
	import { getById } from '@/api/sysConfig';
	import * as Auth from '@/api/auth.js';
	// 使用ES模块导入语法
	import { navigate as publicNavigate } from '@/utils/public.js';
	// 下拉刷新状态
	const refreshing = ref(false);
	// 上拉加载状态
	const loading = ref(false);
	// 是否加载完成
	const finished = ref(false);
	// 当前页码
	const page = ref(1);
	// 每页数量
	const pageSize = ref(5);
	// 薪资列表数据
	const salaryList = ref([]);
	// 通知数量
	const tipCount = ref(5);
	// 资产显示状态
	const showAsset = ref(false);
	const userInfo = ref(
		{ 
			info: {
				name: '---',
				jobName: '---',
				avatar: '/static/logo.png',
			}, 
							lastAmountAdd: 0,
				amountAddSum: 0,
			amount: 0 
		}
	);
	// 切换资产显示/隐藏
	const toggleAssetVisibility = () => {
		showAsset.value = !showAsset.value;
	};
	const flushInfo = () => {
	  Auth.getInfo().then(res => {
	    if (res.code == 200) {
	      // console.log(res.data)
	      uni.setStorageSync('userInfo', JSON.stringify(res.data));
	      // console.log("userInfo", uni.getStorageSync('userInfo'));
	      userInfo.value = res.data
	    }
	  })
	}
	const assetData = reactive({
		rate: 2.01
	}); 
	const getRate = () =>{
		getById(1).then(res=>{
			if(res.code == 200){
				assetData.rate = parseFloat(res.data.vo.value) * 365
			}else if(res.code === 401){
				loading.value = false
			}else{
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				});
				console.error(res)
			}
		}).catch(err=>{
			console.err(err)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			});
		})
	// getById(2).then(res=>{
		// 	if(res.code == 200){
		// 		assetData.withRate = parseFloat(res.data.value).toFixed(4)
		// 	}else{
	//     uni.showToast({
	//       title: '加载失败',
	//       icon: 'none'
	//     });
	//     console.error(res)
	//   }
		// }).catch(err=>{
	//   console.err(err)
	//   uni.showToast({
	//     title: '加载失败',
	//     icon: 'none'
	//   });
		// })
	}
	// flushInfo()
	// const flushInfo = () => { 
	// 	userInfo.value = JSON.parse(uni.getStorageSync('userInfo'));
	// 	console.log('userInfo', userInfo)
	// }
	// 加载薪资数据
	const loadSalaryData = (isFlush=false) => {
		if (isFlush) {
			page.value = 1
		}
		let tmp = JSON.parse(uni.getStorageSync('userInfo'))
		getListByVo({},{
			page: page.value,
			size: pageSize.value
		}).then(res => {
			if (res.code == 200) {
				if (page.value == 1) {
					salaryList.value.splice(0, salaryList.value.length)
				}
				if(res.data.total > salaryList.value.length){
					salaryList.value = salaryList.value.concat(res.data.list)
					page.value++;
				}else{
					
					finished.value = true;
				}
				loading.value = false
			}else if(res.code === 401){
				loading.value = false
			}else{
				loading.value = false
				console.log(res.msg)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				});
			}
		}).catch(err => {
			loading.value = false
			console.log(err.msg)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			});
		});
		// const mockData = [
		// 			{ id: 1, name: '张三', position: '产品经理', month: '8月', amount: '11134', status: 'pending', statusText: '待确认' },
		// 			{ id: 2, name: '张三', position: '产品经理', month: '7月', amount: '11134', status: 'confirmed', statusText: '已确认' },
		// 	{ id: 3, name: '张三', position: '产品经理', month: '6月', amount: '11134', status: 'disputed', statusText: '已提交异议' },
		// 	{ id: 4, name: '张三', position: '产品经理', month: '5月', amount: '11134', status: 'confirmed', statusText: '已确认' },
		// 	{ id: 5, name: '张三', position: '产品经理', month: '4月', amount: '11134', status: 'pending', statusText: '待确认' }
		
		// ];
		// // 模拟分页数据
		// const start = (page.value - 1) * pageSize.value;
		// const end = start + pageSize.value;
		// const pageData = mockData.slice(start, end);
		
		// // 添加到列表
		// if (page.value === 1) {
		// 	salaryList.value = pageData;
		// } else {
		// 	salaryList.value = [...salaryList.value, ...pageData];
		// }
		
		// 判断是否加载完成
		// finished.value = end >= mockData.length;
	};
	
	// 下拉刷新处理 - 强制重置版
	const onRefresh = () => {
		// 重置分页状态
		page.value = 1;
		finished.value = false;
		
		// 先设置refreshing为true
		refreshing.value = true;
		
		// 执行数据加载
		loadSalaryData(true);
		
		// 强制重置refreshing状态的三步策略
		setTimeout(() => {
			// 第一步：先设置为false
			refreshing.value = false;
			
			// 第二步：立即再次设置为false（强制刷新）
			setTimeout(() => {
				refreshing.value = false;
			},
			0);
		},
		200);
	}
	
	// 上拉加载处理
	const onLoad = () => {
		// 防止重复加载
		if (finished.value) return;
		
		// 设置加载状态
		loading.value = true;
		loadSalaryData();
		// // 模拟网络请求
		// setTimeout(() => {
		// 	page.value++;
			
		// 	loading.value = false;
		// }, 1000);
	};
	
	// 确认薪资
	const confirmSalary = (id) => {
		// 查找并更新状态
		const item = salaryList.value.find(item => item.id === id);
		if (item) {
			item.status = 'confirmed';
			item.statusText = '已确认';
			// 显示成功提示
			uni.showToast({
				title: '确认成功',
				icon: 'success'
			});
		}
	};
	
	// 处理图标点击
	const handleIconClick = () => {
		// 这里可以实现点击图标的功能，比如查看通知
		// 跳转到详情页面
		uni.navigateTo({
			url: '/pages/notice/notice'
		});
	};
	
	// 获取状态对应的样式类
	const getStatusClass = (status) => {
		switch (status) {
			case '2':
				return 'status-pending';
			case '5':
				return 'status-confirmed';
			case '4':
				return 'status-disputed';
			default:
				return '';
		}
	};
	const getStatusText = (state) => {
		// 确保state是字符串类型并去除可能的空格
		const stateStr = String(state).trim();
		switch (stateStr) {
			case '2':
				return '待确认';
			case '5':
				return '已确认';
			case '4':
				return '已提交异议';
			case '0':
				return '未处理'; // 处理state为0的情况
			default:
				return '未知状态'; // 提供默认文本而非空字符串
		}
	};
	const monthFormat = (month) => {
		// 确保month是字符串类型
		const monthStr = String(month);
		// 匹配完整的日期时间格式 YYYY-MM-DD HH:MM:SS
		const fullDateMatch = monthStr.match(/^(\d{4})-(\d{2})-(\d{2})/);
		if (fullDateMatch) {
			// return `${fullDateMatch[1]}年${fullDateMatch[2]}月${fullDateMatch[3]}日`;
			return `${fullDateMatch[1]}年${fullDateMatch[2]}月`;
		}
		// // 匹配年月格式 YYYY-MM
		// const yearMonthMatch = monthStr.match(/^(\d+)-(\d+)$/);
		// if (yearMonthMatch) {
		// 	return `${yearMonthMatch[1]}年${yearMonthMatch[2]}月`;
		// }
		// 返回原始值（如果都不匹配）
		return monthStr;
	};
	// 跳转到详情页
	const goToDetail = (id) => {
		// 跳转到详情页面
		uni.navigateTo({
			url: '/pages/detail/detail?id=' + id
		});
	};
	
	// 组件挂载时加载数据
	onMounted(() => {
		// loadSalaryData();
	});
	// 组件挂载时的初始化
	onShow(() => {
		// 可以在这里加载用户信息、资产数据等
		flushInfo();
		// 执行数据加载
		loadSalaryData(true);
		getRate();
		console.log('我的页面已加载');
	});
</script>

<style lang="scss">
	.status-bar-placeholder {
		height: 44px;
	}
	
	.header {
		height: 48px;
		background-color: transparent;
		display: flex;
		align-items: center;
		padding: 0 16px;
	}
	
	/* 自定义徽章样式 */
	.custom-icon-badge {
		display: inline-flex;
		position: relative;
		padding: 4px;
		border-radius: 4px;
	}
	
	.custom-badge {
		position: absolute;
		top: 0;
		right: 0;
		height: 18px;
		padding: 0 6px;
		line-height: 18px;
		font-size: 12px;
		color: #fff;
		background-color: #ff3b30;
		border-radius: 10px;
		text-align: center;
		transform: translate(30%, -30%);
	}
	
	.header-title {
		color: #fff;
		font-size: 20px;
		font-weight: bold;
		flex: 1;
		text-align: left;
		margin-right: 22px;
	}
	
	.salary-item {
		margin: 12px;
		padding: 16px;
		background-color: #fff;
		border-radius: 8px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
		touch-action: manipulation;
	}
	
	.u-page {
		background: linear-gradient(180deg, #4A90E2 0%, #fff 100%);
		min-height: 80vh;
	}
	
	.employee-info {
		display: flex;
		align-items: center;
		margin-bottom: 12px;
	}
	
	.employee-name {
		font-size: 20px;
		font-weight: bold;
		margin-right: 8px;
	}
	
	.position-tag {
		font-size: 14px;
		color: #4d4f51;
		background-color: #eaf1fa;
		padding: 2px 8px;
		border-radius: 4px;
		margin-left: 8px;
	}
	
	.bottom-container {
		margin-top: 5vh;
		width: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	
	.salary-amount {
		flex: 1;
		margin-bottom: 0;
	}
	
	.status-display {
		margin-left: auto;
	}
	
	.month {
		margin-left: auto;
		font-size: 17px;
		color: #000;
	}
	
	.amount-label {
		font-size: 14px;
		color: #666;
	}
	
	.amount-value {
		font-size: 20px;
		font-weight: bold;
		color: #e64340;
	}
	
	.status-display {
		text-align: right;
		color: #666;
		font-size: 14px;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		touch-action: manipulation;
	}
	
	.status-text {
		margin-right: 4px;
	}
	
	.status-pending {
		color: #b33b17;
	}
	
	.status-confirmed {
		color: #257f69;
	}
	
	.status-disputed {
		color: #b06e20;
	}
	/* 资产卡片样式 */
	.asset-card {
		margin: 0 12px 20px;
		padding: 16px;
		background-color: #fff;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}
	
	.asset-header {
		margin-bottom: 15px;
	}
	
	.asset-title-container {
		display: flex;
		align-items: center;
		margin-bottom: 5px;
		flex-wrap: nowrap;
	}
	
	.asset-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		margin-right: 8px;
		flex-shrink: 0;
	}
	
	.asset-tag {
		font-size: 12px;
		color: #666;
		background-color: #ffcba7;
		padding: 3px 8px;
		border-radius: 12px;
		margin-left: 10px;
		flex-shrink: 0;
	}
	
	.asset-amount {
		font-size: 28px;
		font-weight: bold;
		color: #333;
		margin: 15px 0;
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}
	
	.amount-arrow {
		margin-left: 10px;
	}
	
	.asset-details {
		display: flex;
		justify-content: flex-start;
		padding-top: 15px;
	}
	
	.asset-detail-divider {
		width: 2px;
		height: 40px;
		margin: 0 20px;
	}
	
	.asset-detail-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.detail-label {
		font-size: 12px;
		color: #666;
		margin-bottom: 5px;
	}
	
	.detail-value {
		font-size: 16px;
		color: #333;
		font-weight: bold;
	}
</style>